<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\IndexApi;
use Illuminate\Support\Facades\Redis;
use App\Model\Goods;
use App\Model\Goodsbrand;
use App\Model\Goodsattr;


class IndexLazyloadApi extends Controller
{
    //
    /**
     * [lazyLoad 处理首页懒加载请求]
     * @param  Request $request [传入对应DIV的sortnum]
     * @return [object]           [[$status => '状态码', $goodsObj => '对应的数据']]
     */
    public function lazyLoad(Request $request)
    {

        //判断进来的sortnum
        switch ($request->sortnum) {
            case "0":
                # code...
                //请求热销商品信息
                $goodsObj = $this->getHotGoods(6);

                break;

            case "1":
                //请求品牌信息
                $goodsObj['brands'] = $this->getBrands();

                break;

            case "2":
                # code...
                $goodsObj = '123';

                break;

            case "3":
                //请求品牌信息
				$goodsObj['brands'] = $this->getBrands();

            	break;

            case "4":

            	$goodsObj = '123';

            	break;

            default:
                # code...
                break;
        }

        if ($goodsObj) {

            return [
                'status' => '200',
                'goodsObj' => $goodsObj,
            ];

        }

        return [
            'status' => '404'
        ];

    }


    /**
     * [getHotGoods 从redis中获取热销商品数据]
     * @return [array]
     */
    public function getHotGoods($num)
    {
        $hotGoodsSet = 'hot_goods_set';
        $hotGoodsHash = 'hot_goods_hash_id:';

        //判断redis中是否有热销商品，如果没有就查询数据库
        if (empty(Redis::sMembers($hotGoodsSet))) {

            $index = new IndexApi();
            $index->hotMysqlGoods();
        }

        $GoodsHashArr = Redis::sRandMember($hotGoodsSet, $num);

        foreach ($GoodsHashArr as $k => $v) {
            $hotGoods[] = Redis::hGetAll($v);
        }
        return $hotGoods;


    }

    /**
     * [getBrands 获取品牌信息]
     * @return [array] [返回一个二维数组]
     */
    public function getBrands()
    {

    	$setBrandKey = 'goods_brands_set_data';

    	$hashBrandKey = 'goods_brands_hash_data:';

        //先判断redis里有没有品牌信息， 如果没有就查询数据库
    	if (empty(Redis::sMembers($setBrandKey))) {

    		$brands = Goodsbrand::select('id', 'brand_name', 'brand_logo')->limit(6)->get()->toArray();

    		foreach($brands as $v) {

    			Redis::sAdd($setBrandKey, $hashBrandKey.$v['id']);

    			Redis::hMset($hashBrandKey.$v['id'], $v);

    		}
    	}

    	$brandsHashArr = Redis::sMembers($setBrandKey);

    	foreach ( $brandsHashArr as $v) {

    		$brands[] = Redis::hGetAll($v);

    	}

    	return $brands;

    }



}
